package com.example.teesystem.filter;

import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理跨域问题
 * @author punch
 * @data 2021-09-27 11:03
 */
//@Component
public class SimpleCORSFilter implements Filter{


    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;

        response.setHeader("Access-Control-Allow-Origin", "*");

        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");

        response.setHeader("Access-Control-Max-Age", "3600");

        //里面加上自定义的请求头部分，token
        response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin,  token, content-type,  X-Requested-With, uid");

        //处理跨域请求头,vue自定义请求头时会先发送options请求
        if (request.getMethod().equals("OPTIONS")) {

            response.setStatus(HttpStatus.SC_OK);

            response.getWriter().write("OPTIONS returns OK");

            return;

        }

        chain.doFilter(req, res);

    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}
}
